<template>
  <div class="activity-container">
    <div class="header-actions">
      <h1>活动中心</h1>
      <div class="action-buttons">
        <el-button type="primary" @click="goToCreateActivity">发布活动</el-button>
        <el-button @click="goToCreateClub">社团入驻</el-button>
      </div>
    </div>
    <!-- 选项卡切换 -->
    <div class="tabs">
      <button :class="{ 'active': currentTab === 'activities' }" @click="switchTab('activities')">活动</button>
      <button :class="{ 'active': currentTab === 'clubs' }" @click="switchTab('clubs')">社团</button>
    </div>

    <!-- 活动列表 -->
    <div v-if="currentTab === 'activities'" class="activities-list">
      <div class="filter-bar">
        <input type="text" v-model="searchKeyword" placeholder="搜索活动..." @input="debounceSearch">
        <select v-model="activityFilter" @change="fetchActivities">
          <option value="">全部活动</option>
          <option value="not_started">未开始报名</option>
          <option value="registration_open">报名中</option>
          <option value="full">已报满</option>
          <option value="ongoing">进行中</option>
          <option value="completed">已结束</option>
          <option value="cancelled">已取消</option>
        </select>
        <select v-model="activityType" @change="fetchActivities">
          <option value="">全部类型</option>
          <option value="academic">学术讲座</option>
          <option value="cultural">文化活动</option>
          <option value="sports">体育活动</option>
          <option value="volunteer">志愿活动</option>
          <option value="competition">比赛竞赛</option>
          <option value="party">聚会活动</option>
        </select>
      </div>
      <div class="activity-cards">
        <div v-for="activity in activities" :key="activity.id" class="activity-card" @click="goToActivityDetail(activity.id)">
          <div class="activity-info">
            <h3>{{ activity.title }}</h3>
            <p class="activity-club">{{ activity.club?.name || '未知社团' }}</p>
            <p class="activity-type">{{ typeMap[activity.activity_type] || '其他' }}</p>
            <p class="activity-time">{{ formatDate(activity.start_time) }}</p>
            <p class="activity-location">{{ activity.location }}</p>
            <div class="activity-status" :class="[(activity.current_participants >= activity.max_participants && activity.status === 'registration_open') ? 'full' : activity.status]">
              {{ (activity.current_participants >= activity.max_participants && activity.status === 'registration_open') ? '已报满' : statusMap[activity.status] }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 社团列表 -->
    <div v-else class="clubs-list">
      <div class="filter-bar">
        <input type="text" v-model="searchKeyword" placeholder="搜索社团..." @input="debounceSearch">
      </div>
      <div class="club-cards">
        <div v-for="club in clubs" :key="club.id" class="club-card" @click="goToClubDetail(club.id)">
          <div class="club-info">
            <h3>{{ club.name }}</h3>
            <p class="club-desc">{{ club.description.substring(0, 50) }}...</p>
            <p class="club-members">{{ club.members }} 成员</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { activityApi } from '@/api'
import { formatDate } from '@/utils/date'
import { debounce } from 'lodash'

const router = useRouter()
const currentTab = ref('activities') // 'activities' 或 'clubs'
const activities = ref([])
const clubs = ref([])
const searchKeyword = ref('')
const activityFilter = ref('')
const activityType = ref('')

// 状态映射
const statusMap = {
  'not_started': '未开始报名',
  'registration_open': '报名中',
  'ongoing': '进行中',
  'completed': '已结束',
  'cancelled': '已取消'
}

// 活动类型映射
const typeMap = {
  'academic': '学术讲座',
  'cultural': '文化活动',
  'sports': '体育活动',
  'volunteer': '志愿活动',
  'competition': '比赛竞赛',
  'party': '聚会活动',
  'other': '其他'
}

// 切换选项卡
const switchTab = (tab) => {
  currentTab.value = tab
  if (tab === 'activities') {
    fetchActivities()
  } else {
    fetchClubs()
  }
}

// 跳转到发布活动页面
const goToCreateActivity = () => {
  router.push('/activity/create')
}

// 跳转到社团入驻页面
const goToCreateClub = () => {
  router.push('/activity/create-club')
}

// 获取活动列表
const fetchActivities = async () => {
  try {
    const params = {
      search: searchKeyword.value,
      status: activityFilter.value,
      type: activityType.value
    }
    console.log('获取活动列表参数:', params);
    const res = await activityApi.getActivities(params)
    console.log('获取活动列表响应:', res);
    console.log('响应数据结构:', JSON.stringify(res, null, 2));
    // 修正数据结构解析：响应拦截器已经提取了response.data，所以直接使用res.data?.list
    activities.value = res.data?.list || []
    console.log('最终活动数据:', activities.value);
  } catch (error) {
    console.error('获取活动失败:', error)
  }
}

// 获取社团列表
const fetchClubs = async () => {
  try {
    const params = {
      search: searchKeyword.value
    }
    const res = await activityApi.getClubs(params)
    clubs.value = res.data  // 修改为直接使用res.data，因为后端返回的data就是社团列表
  } catch (error) {
    console.error('获取社团失败:', error)
  }
}

// 防抖搜索
const debounceSearch = debounce(() => {
  if (currentTab.value === 'activities') {
    fetchActivities()
  } else {
    fetchClubs()
  }
}, 500)

// 跳转到活动详情
const goToActivityDetail = (activityId) => {
  router.push({ name: 'activityDetail', params: { id: activityId } })
}

// 跳转到社团详情
const goToClubDetail = (clubId) => {
  router.push({ name: 'clubDetail', params: { id: clubId } })
}

// 页面加载时执行
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activity-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.activity-status.full {
  background-color: #fef0f0;
  color: #e6a23c;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
}

.tabs button {
  padding: 10px 20px;
  background-color: #f0f0f0;
  border: none;
  cursor: pointer;
}

.tabs button.active {
  background-color: #42b983;
  color: white;
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.filter-bar input,
.filter-bar select {
  padding: 10px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  flex: 1;
  min-width: 150px;
}

.filter-bar input,
.filter-bar select {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.activity-cards,
.club-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.activity-card,
  .club-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 15px;
    cursor: pointer;
    transition: box-shadow 0.3s;
    min-height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

.activity-card:hover,
.club-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 移除了列表中的图片显示 */

.activity-info,
.club-info {
  padding: 15px;
}

.activity-type {
  display: inline-block;
  padding: 3px 8px;
  background-color: #f0f7ff;
  color: #4e89e8;
  border-radius: 4px;
  font-size: 12px;
  margin-bottom: 8px;
}

.activity-card h3,
.club-card h3 {
  margin-bottom: 8px;
  font-size: 18px;
}

.activity-club,
.club-desc {
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
}

.activity-time,
.activity-location,
.club-members {
  color: #999;
  font-size: 12px;
  margin-bottom: 4px;
}

.activity-status {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
}

.activity-status.not_started {
  background-color: #f0f9eb;
  color: #67c23a;
}

.activity-status.ongoing {
  background-color: #ecf5ff;
  color: #4096ff;
}

.activity-status.ended {
  background-color: #f5f5f5;
  color: #909399;
}

.activity-status.cancelled {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>